#include "class-engine.h"

void cEngine::getJoypad(sJoypad &joypad){

		SDL_JoystickUpdate();

		// Get the sticks
		joypad.leftX  = SDL_JoystickGetAxis(stick, 0);
		joypad.leftY  = SDL_JoystickGetAxis(stick, 1);
		joypad.rightX = SDL_JoystickGetAxis(stick, 3);
		joypad.rightY = SDL_JoystickGetAxis(stick, 4); // axis 2 for ps2 and xbox 1 controller

		/* Get the Left Stick Vector */

		fTempNum = sqrt((float)(joypad.leftX*joypad.leftX)+(float)(joypad.leftY*joypad.leftY));

		// cap the maximum velocity
		if (fTempNum > STICK_MAX_TRAVEL){
			fTempNum = STICK_MAX_TRAVEL;
		}

		// convert the velocity to a percentage
		fTempNum = (fTempNum / STICK_MAX_TRAVEL) * 100;

		// apply a deadzone
		if (fTempNum > STICK_DEADZONE){
			joypad.leftVector.velocity	= fTempNum;
			joypad.leftVector.angle		= atan2((float)joypad.leftY,(float)joypad.leftX);
		}else{
			joypad.leftVector.velocity	= 0;
		}

		/* Get the Right Stick Vector */

		fTempNum = sqrt((float)(joypad.rightX*joypad.rightX)+(float)(joypad.rightY*joypad.rightY));

		// cap the maximum velocity
		if (fTempNum > STICK_MAX_TRAVEL){
			fTempNum = STICK_MAX_TRAVEL;
		}

		// convert the velocity to a percentage
		fTempNum = (fTempNum / STICK_MAX_TRAVEL) * 100;

		// apply a deadzone
		if (fTempNum > STICK_DEADZONE){
			joypad.rightVector.velocity	= fTempNum;
			joypad.rightVector.angle	= atan2((float)joypad.rightX,(float)joypad.rightY);
		}else{
			joypad.rightVector.velocity	= 0;
		}


		// Get the triggers
		joypad.triggers = SDL_JoystickGetAxis(stick, 2);

		joypad.hat = SDL_JoystickGetHat(stick, 0);

		joypad.a = SDL_JoystickGetButton(stick, 0);
		joypad.b = SDL_JoystickGetButton(stick, 1);
		joypad.x = SDL_JoystickGetButton(stick, 2);
		joypad.y = SDL_JoystickGetButton(stick, 3);

		joypad.left  = SDL_JoystickGetButton(stick, 4);
		joypad.right = SDL_JoystickGetButton(stick, 5);
		
		joypad.start  = SDL_JoystickGetButton(stick, 6);
		joypad.select = SDL_JoystickGetButton(stick, 7);

		joypad.leftStick  = SDL_JoystickGetButton(stick, 8);
		joypad.rightStick = SDL_JoystickGetButton(stick, 9);

		joypad.hat = SDL_JoystickGetHat(stick, 0);

		if (joypad.hat == SDL_HAT_UP)
			cout << "SDL_HAT_UP" << endl;
		
		else if (joypad.hat == SDL_HAT_DOWN)
			cout << "SDL_HAT_DOWN" << endl;
		
		else if (joypad.hat == SDL_HAT_LEFTUP)
			cout << "SDL_HAT_LEFTUP" << endl;

		else if (joypad.hat == SDL_HAT_LEFT)
			cout << "SDL_HAT_LEFT" << endl;

		else if (joypad.hat == SDL_HAT_LEFTDOWN)
			cout << "SDL_HAT_LEFTDOWN" << endl;		

		else if (joypad.hat == SDL_HAT_RIGHTUP)
			cout << "SDL_HAT_RIGHTUP" << endl;

		else if (joypad.hat == SDL_HAT_RIGHT)
			cout << "SDL_HAT_RIGHT" << endl;

		else if (joypad.hat == SDL_HAT_RIGHTDOWN)
			cout << "SDL_HAT_RIGHTDOWN" << endl;
		
}